package com.niodata.md.rdb.crawler;

import com.niodata.md.rdb.model.Catalog;
import com.niodata.md.rdb.model.DbInfo;
import java.sql.DatabaseMetaData;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * retrieve database information.
 */
public class DbInfoRetrieval extends AbstractRetrieval {
  @Override
  public List<MetaDataRetrieval> retrieveMetaData() throws Exception {
    DbInfo dbInfo = this.parseDbInfo(this.getMetaData());
    this.getCatalog().setDbInfo(dbInfo);
    return Collections.emptyList();
  }

  private DbInfo parseDbInfo(DatabaseMetaData metaData) throws Exception {
    DbInfo dbInfo = new DbInfo();
    dbInfo.setDriverName(metaData.getDriverName());
    dbInfo.setProductName(metaData.getDatabaseProductName());
    dbInfo.setProductVersion(metaData.getDatabaseProductVersion());
    dbInfo.setDriverVersion(metaData.getDriverVersion());
    dbInfo.setDatabaseMajorVersion(metaData.getDatabaseMajorVersion());
    dbInfo.setDatabaseMinorVersion(metaData.getDatabaseMinorVersion());
    String url = metaData.getURL();
    String regex = "jdbc:([^:]+)://([^:]+):([0-9]+)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(url);
    if (matcher.find()) {
      String serverType = matcher.group(1);
      String host = matcher.group(2);
      int port = Integer.parseInt(matcher.group(3));
      dbInfo.setDatabaseServerType(serverType);
      dbInfo.setPort(port);
      dbInfo.setHost(host);
    } else {
      throw new RuntimeException("parse host/port failed from url:" + url);
    }
    return dbInfo;
  }
}
